﻿package dk.gaming.rummikub.Utils
{
	import dk.gaming.rummikub.primitive.Tile;
	import fl.motion.Color;
	import dk.gaming.rummikub.enums.SetType;
	
	public class Utility
	{
		
		public static function CheckSet(tiles:Array):SetType
		{
			if(CheckRun(tiles))
				return new SetType(SetType.run);
			else if(CheckGroup(tiles))
				return new SetType(SetType.group);
			else
				return new SetType(SetType.notset);
		}
		
		public static function CheckRun(tiles:Array):Boolean
		{
			var run : Boolean = true;
			var colorsame : Boolean = true;
			var numbers : Array = new Array();
			var prevnum : Number;
			
			for(var i : Number = 0; i<tiles.length; i++)
			{
				numbers.push( (tiles[i] as Tile).Number as Number );
				if((tiles[i] as Tile).Color.tintColor != (tiles[0] as Tile).Color.tintColor)
				{
					colorsame = false;
					break;
				}
			}
			
			if(!colorsame) return false;
			
			numbers.sort(Array.NUMERIC);
			for(var i : Number = 0; i<numbers.length; i++)
			{
				if(i == 0)
				prevnum = numbers[i];
				else
				{
					if (numbers[i] != prevnum+1)
					{
						run = false;
						break;
					}
					else if(numbers[i] == prevnum+1)
					{
						prevnum = numbers[i];
					}
				}
			}
			return run;
		}
		
		
		public static function CheckGroup(tiles:Array):Boolean
		{
			var group : Boolean = true;
			var numbers : Array = new Array();
			var stacknumbers : Array = new Array();
			var colors : Array = new Array();
			var stackcolors : Array = new Array();
			
			for(var i : Number = 0; i<tiles.length; i++)
			{	
				numbers.push( (tiles[i] as Tile).Number );	
				colors.push( (tiles[i] as Tile).Color.tintColor );
			}
			
			var alluniquecolors : Boolean = true;
			for(var i : Number = 0; i<numbers.length; i++)
			{
				if( UniqueInArray(colors[i], stackcolors) )
				{
					stackcolors.push(colors[i]);
				}
				else
				{
					alluniquecolors = false;
					break;
				}
			}
			
			if(!alluniquecolors) return false;
			
			var samenumber : Boolean = true;
			for(var i : Number = 0; i<colors.length; i++)
			{
				if(colors[i] != colors[0])
				{
					samenumber = false;
					break;
				}
			}
			return samenumber;
		}
		
		public static function UniqueInArray(element:* array:Array):Boolean
		{
			var unique : Boolean = true;
			for(var i : Number = 0; i<array.length; i++)
			{
				if(array[i] == element)
				{
					unique = false;
					break;
				}
			}
			return unique;
		}
		
		
		public static function ValidateEmail(Email:String):Boolean
		{
			
		}
		
		public static function ValidatePassword(pw:String):Boolean
		{
			
		}
		
		public static function Definite(value:Number):Number
		{
			if(value < 0)
			{
				value = -value;
			}
			return value;
		}
		
		
		
	}
	
	
	
	
}